import axios from "axios";
import fs from "fs";
import path from "path";

async function download(url, fileDir = "output", filePath = "document.pdf") {
  try {
    const response = await axios({
      url,
      method: "GET",
      responseType: "stream",
    });

    // 尝试从content-disposition头部提取文件名
    const contentDisposition = response.headers["content-disposition"];
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename="?([^"]+)"?/i);
      if (filenameMatch && filenameMatch[1]) {
        filePath = path.join(fileDir, filenameMatch[1]);
      } else {
        filePath = path.join(fileDir, path.basename(filePath));
      }
    }

    // 确保目录存在
    if (!fs.existsSync(fileDir)) {
      console.log("确保目录存在");
      fs.mkdirSync(fileDir, { recursive: true });
    }

    console.log("createWriteStream");
    const writer = fs.createWriteStream(filePath);
    response.data.pipe(writer);

    return new Promise((resolve, reject) => {
      writer.on("finish", () => resolve(filePath));
      writer.on("error", reject);
    });
  } catch (error) {
    console.error("下载失败:", error);
    throw error;
  }
}

export default download;
